<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/agul.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/agul.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/agul.png?v=5.1.4">






  <meta name="keywords" content="FCC,正则," />




  


  <link rel="alternate" href="/atom.xml" title="Agul'blog" type="application/atom+xml" />






<meta name="description" content="正则表达式介绍正则表达式是表示搜索模式的特殊字符串。也被称为“regex”或“regexp”，它们可以帮助程序员匹配、搜索和替换文本。由于一些字符具有特殊的含义，正则表达式可能会显得晦涩难懂。我们的目标是将这些符号和文本组合成一个你想要的匹配模式，但这只是你想要的。本节将介绍字符、一些快捷方式以及编写正则表达式的常用用法。 使用测试方法在编程语言中，正则表达式用于匹配指定的字符串。通过正则表达式创">
<meta property="og:type" content="article">
<meta property="og:title" content="正则表达式">
<meta property="og:url" content="https://ultraman-agul.github.io/2020/05/07/04%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/index.html">
<meta property="og:site_name" content="Agul&#39;blog">
<meta property="og:description" content="正则表达式介绍正则表达式是表示搜索模式的特殊字符串。也被称为“regex”或“regexp”，它们可以帮助程序员匹配、搜索和替换文本。由于一些字符具有特殊的含义，正则表达式可能会显得晦涩难懂。我们的目标是将这些符号和文本组合成一个你想要的匹配模式，但这只是你想要的。本节将介绍字符、一些快捷方式以及编写正则表达式的常用用法。 使用测试方法在编程语言中，正则表达式用于匹配指定的字符串。通过正则表达式创">
<meta property="article:published_time" content="2020-05-07T03:18:24.108Z">
<meta property="article:modified_time" content="2020-05-07T03:24:37.448Z">
<meta property="article:author" content="agul">
<meta property="article:tag" content="FCC">
<meta property="article:tag" content="正则">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://ultraman-agul.github.io/2020/05/07/04正则表达式/"/>





  <title>正则表达式 | Agul'blog</title>
  








<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Agul'blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Record a good life</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://ultraman-agul.github.io/2020/05/07/04%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="agul">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/agul1.png">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Agul'blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">正则表达式</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-05-07T11:18:24+08:00">
                2020-05-07
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index">
                    <span itemprop="name">web前端</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/%E7%AC%94%E8%AE%B0/" itemprop="url" rel="index">
                    <span itemprop="name">笔记</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/%E7%AC%94%E8%AE%B0/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/" itemprop="url" rel="index">
                    <span itemprop="name">正则表达式</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="正则表达式"><a href="#正则表达式" class="headerlink" title="正则表达式"></a>正则表达式</h1><h3 id="介绍"><a href="#介绍" class="headerlink" title="介绍"></a>介绍</h3><p>正则表达式是表示搜索模式的特殊字符串。也被称为“regex”或“regexp”，它们可以帮助程序员匹配、搜索和替换文本。由于一些字符具有特殊的含义，正则表达式可能会显得晦涩难懂。我们的目标是将这些符号和文本组合成一个你想要的匹配模式，但这只是你想要的。本节将介绍字符、一些快捷方式以及编写正则表达式的常用用法。</p>
<h3 id="使用测试方法"><a href="#使用测试方法" class="headerlink" title="使用测试方法"></a>使用测试方法</h3><p>在编程语言中，正则表达式用于匹配指定的字符串。通过正则表达式创建匹配模式（规则）可以帮你完成指定匹配。</p>
<p>如果你想要在字符串<code>&quot;The dog chased the cat&quot;</code>中匹配到<code>&quot;the&quot;</code>这个单词，你可以使用如下正则表达式：<code>/the/</code>。注意，正则表达式中不需要引号。</p>
<p>JavaScript 中有多种使用正则表达式的方法。测试正则表达式的一种方法是使用<code>.test()</code>方法。<code>.test()</code>方法会把你编写的正则表达式应用到一个字符串（即括号内的内容），如果你的匹配模式成功匹配到字符，则返回<code>true</code>，反之，返回<code>false</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> testStr = <span class="string">"freeCodeCamp"</span>;</span><br><span class="line"><span class="keyword">let</span> testRegex = <span class="regexp">/Code/</span>;</span><br><span class="line">testRegex.test(testStr);</span><br><span class="line"><span class="comment">// Returns true</span></span><br></pre></td></tr></table></figure>



<h3 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h3><p>在字符串中搜寻<code>&quot;Kevin&quot;</code>的示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> testStr = <span class="string">"Hello, my name is Kevin."</span>;</span><br><span class="line"><span class="keyword">let</span> testRegex = <span class="regexp">/Kevin/</span>;</span><br><span class="line">testRegex.test(testStr);</span><br><span class="line"><span class="comment">// Returns true</span></span><br></pre></td></tr></table></figure>

<p>任何其他形式的<code>&quot;Kevin&quot;</code>都不会被匹配。例如，正则表达式<code>/Kevin/</code>不会匹配<code>&quot;kevin&quot;</code>或者<code>&quot;KEVIN&quot;</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> wrongRegex = <span class="regexp">/kevin/</span>;</span><br><span class="line">wrongRegex.test(testStr);</span><br><span class="line"><span class="comment">// Returns false</span></span><br></pre></td></tr></table></figure>



<h3 id="多种模式匹配文字字符串"><a href="#多种模式匹配文字字符串" class="headerlink" title="多种模式匹配文字字符串 |"></a>多种模式匹配文字字符串 |</h3><p>使用正则表达式<code>/coding/</code>，你可以在其他字符串中查找<code>&quot;coding&quot;</code>。</p>
<p>这对于搜寻单个字符串非常有用，但仅限于一种匹配模式。你可以使用<code>|</code>操作符来匹配多个规则。</p>
<p>此操作符匹配在它之前或之后的匹配模式。例如，如果你想匹配<code>&quot;yes&quot;</code>或<code>&quot;no&quot;</code>，你需要的正则表达式是<code>/yes|no/</code>。</p>
<p>你还可以匹配多个规则，这可以通过添加更多的匹配模式来实现。这些匹配模式将包含更多的<code>|</code>操作符来分隔它们，比如<code>/yes|no|maybe/</code>。</p>
<h3 id="忽略大小写-i"><a href="#忽略大小写-i" class="headerlink" title="忽略大小写 i"></a>忽略大小写 i</h3><p>到目前为止，你已经了解了如何用正则表达式来执行字符串的文字匹配。但有时候，你可能也想匹配不同的英文字母大小写。</p>
<p>大小写（或者字母大小写）是大写字母和小写字母的区别。大写字母的例子有<code>&quot;A&quot;</code>、<code>&quot;B&quot;</code>和<code>&quot;C&quot;</code>。小写字母的例子有<code>&quot;a&quot;</code>、<code>&quot;b&quot;</code>和<code>&quot;c&quot;</code>。</p>
<p>你可以使用标志（flag）来匹配这两种情况。标志有很多，不过这里我们只关注忽略大小写的标志——<strong><code>i</code></strong>。你可以通过将它附加到正则表达式之后来使用它。这里给出使用该标志的一个实例<code>/ignorecase/i</code>。这个字符串可以匹配字符串<code>&quot;ignorecase&quot;</code>、<code>&quot;igNoreCase&quot;</code>和<code>&quot;IgnoreCase&quot;</code>。</p>
<h3 id="提取匹配项-match"><a href="#提取匹配项-match" class="headerlink" title="提取匹配项 .match()"></a>提取匹配项 .match()</h3><p>到目前为止，你只是检查了一个匹配模式是否存在于字符串中。你还可以使用<code>.match()</code>方法来提取你找到的实际匹配项。</p>
<p>请使用字符串来调用<code>.match()</code>方法，并在括号内传入正则表达式。以下是一个示例：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"Hello, World!"</span>.match(<span class="regexp">/Hello/</span>);</span><br><span class="line"><span class="comment">// Returns ["Hello"]</span></span><br><span class="line"><span class="keyword">let</span> ourStr = <span class="string">"Regular expressions"</span>;</span><br><span class="line"><span class="keyword">let</span> ourRegex = <span class="regexp">/expressions/</span>;</span><br><span class="line">ourStr.match(ourRegex);</span><br><span class="line"><span class="comment">// Returns ["expressions"]</span></span><br></pre></td></tr></table></figure>

<blockquote>
</blockquote>
<h3 id="全局匹配-g"><a href="#全局匹配-g" class="headerlink" title="全局匹配  g"></a>全局匹配  g</h3><p>若要多次搜寻或提取匹配模式，你可以使用<code>g</code>标志。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> testStr = <span class="string">"Repeat, Repeat, Repeat"</span>;</span><br><span class="line"><span class="keyword">let</span> repeatRegex = <span class="regexp">/Repeat/g</span>;</span><br><span class="line">testStr.match(repeatRegex);</span><br><span class="line"><span class="comment">// Returns ["Repeat", "Repeat", "Repeat"]</span></span><br></pre></td></tr></table></figure>



<h3 id="通配符-匹配任何内容"><a href="#通配符-匹配任何内容" class="headerlink" title="通配符.匹配任何内容  ."></a>通配符.匹配任何内容  .</h3><p>有时你不会（或不需要）知道匹配模式中的确切字符。如果要精确匹配到完整的单词那出现一个拼写错误就会匹配不到。幸运的是，你可以使用通配符<code>.</code>来处理这种情况。</p>
<p>通配符<code>.</code>将匹配任何一个字符。通配符也叫<code>dot</code>或<code>period</code>。你可以像使用正则表达式中任何其他字符一样使用通配符。例如，如果你想匹配<code>&quot;hug&quot;</code>、<code>&quot;huh&quot;</code>、<code>&quot;hut&quot;</code>和<code>&quot;hum&quot;</code>，你可以使用正则表达式<code>/hu./</code>匹配以上四个单词。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> humStr = <span class="string">"I'll hum a song"</span>;</span><br><span class="line"><span class="keyword">let</span> hugStr = <span class="string">"Bear hug"</span>;</span><br><span class="line"><span class="keyword">let</span> huRegex = <span class="regexp">/hu./</span>;</span><br><span class="line">humStr.match(huRegex); <span class="comment">// Returns ["hum"]</span></span><br><span class="line">hugStr.match(huRegex); <span class="comment">// Returns ["hug"]</span></span><br></pre></td></tr></table></figure>



<h3 id="单个字符有多种可能性"><a href="#单个字符有多种可能性" class="headerlink" title="单个字符有多种可能性 []"></a>单个字符有多种可能性 []</h3><p>你已经了解了如何匹配文字匹配模式（<code>/literal/</code>）和通配符（<code>/./</code>）。这是正则表达式的两种极端情况，一种是精确匹配，而另一种则是匹配所有。在这两种极端情况之间有一个平衡选项。</p>
<p>你可以使用<code>字符集</code>搜寻具有一定灵活性的文字匹配模式。字符集允许你通过把它们放在方括号（<code>[</code>和<code>]</code>）之间的方式来定义一组你需要匹配的字符串。</p>
<p>例如，你想要匹配<code>&quot;bag&quot;</code>、<code>&quot;big&quot;</code>和<code>&quot;bug&quot;</code>，但是不想匹配<code>&quot;bog&quot;</code>。你可以创建正则表达式<code>/b[aiu]g/</code>来执行此操作。<code>[aiu]</code>是只匹配字符<code>&quot;a&quot;</code>、<code>&quot;i&quot;</code>或者<code>&quot;u&quot;</code>的字符集。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> bigStr = <span class="string">"big"</span>;</span><br><span class="line"><span class="keyword">let</span> bagStr = <span class="string">"bag"</span>;</span><br><span class="line"><span class="keyword">let</span> bugStr = <span class="string">"bug"</span>;</span><br><span class="line"><span class="keyword">let</span> bogStr = <span class="string">"bog"</span>;</span><br><span class="line"><span class="keyword">let</span> bgRegex = <span class="regexp">/b[aiu]g/</span>;</span><br><span class="line">bigStr.match(bgRegex); <span class="comment">// Returns ["big"]</span></span><br><span class="line">bagStr.match(bgRegex); <span class="comment">// Returns ["bag"]</span></span><br><span class="line">bugStr.match(bgRegex); <span class="comment">// Returns ["bug"]</span></span><br><span class="line">bogStr.match(bgRegex); <span class="comment">// Returns null</span></span><br></pre></td></tr></table></figure>



<h3 id="英文字母-a-z"><a href="#英文字母-a-z" class="headerlink" title="英文字母 [a-z]"></a>英文字母 [a-z]</h3><p>你了解了如何使用<code>字符集</code>来指定要匹配的一组字符串，但是当你需要匹配大量字符（例如，字母表中的每个字母）时，有一种写法可以让实现这个功能变得简短。</p>
<p>在<code>字符集</code>中，你可以使用<code>连字符</code>（<code>-</code>）来定义要匹配的字符范围。</p>
<p>例如，要匹配小写字母<code>a</code>到<code>e</code>，你可以使用<code>[a-e]</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> catStr = <span class="string">"cat"</span>;</span><br><span class="line"><span class="keyword">let</span> batStr = <span class="string">"bat"</span>;</span><br><span class="line"><span class="keyword">let</span> matStr = <span class="string">"mat"</span>;</span><br><span class="line"><span class="keyword">let</span> bgRegex = <span class="regexp">/[a-e]at/</span>;</span><br><span class="line">catStr.match(bgRegex); <span class="comment">// Returns ["cat"]</span></span><br><span class="line">batStr.match(bgRegex); <span class="comment">// Returns ["bat"]</span></span><br><span class="line">matStr.match(bgRegex); <span class="comment">// Returns null</span></span><br></pre></td></tr></table></figure>



<h3 id="数字和字母-a-z0-9"><a href="#数字和字母-a-z0-9" class="headerlink" title="数字和字母  [a-z0-9]"></a>数字和字母  [a-z0-9]</h3><p>使用连字符（<code>-</code>）匹配字符范围并不仅限于字母。它还可以匹配一系列数字。</p>
<p>例如，<code>/[0-5]/</code>匹配<code>0</code>和<code>5</code>之间的任意数字，包含<code>0</code>和<code>5</code>。</p>
<p>此外，还可以在单个字符集中组合一系列字母和数字。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> jennyStr = <span class="string">"Jenny8675309"</span>;</span><br><span class="line"><span class="keyword">let</span> myRegex = <span class="regexp">/[a-z0-9]/ig</span>;</span><br><span class="line"><span class="comment">// matches all letters and numbers in jennyStr</span></span><br><span class="line">jennyStr.match(myRegex);</span><br></pre></td></tr></table></figure>



<h3 id="不想匹配的字符"><a href="#不想匹配的字符" class="headerlink" title="不想匹配的字符 [^]"></a>不想匹配的字符 [^]</h3><p>你也可以创建一个你不想匹配的字符集合。这些类型的字符集称为<code>否定字符集</code>。</p>
<p>要创建<code>否定字符集</code>，你需要在开始括号后面和不想匹配的字符前面放置<code>插入字符</code>（即<code>^</code>）。</p>
<p>例如，<code>/[^aeiou]/gi</code>匹配所有非元音字符。注意，字符<code>.</code>、<code>!</code>、<code>[</code>、<code>@</code>、<code>/</code>和空白字符等也会被匹配，该否定字符集仅排除元音字符。</p>
<h3 id="出现一次或多次的字符"><a href="#出现一次或多次的字符" class="headerlink" title="出现一次或多次的字符  +"></a>出现一次或多次的字符  +</h3><p>至少出现一次，并且可能重复出现。</p>
<p>使用<code>+</code>符号来检查情况是否如此。记住，字符或匹配模式<strong>必须一个接一个地连续出现</strong>。</p>
<p>例如，<code>/a+/g</code>会在<code>&quot;abc&quot;</code>中匹配到一个匹配项，并且返回<code>[&quot;a&quot;]</code>。因为<code>+</code>的存在，它也会在<code>&quot;aabc&quot;</code>中匹配到一个匹配项，然后返回<code>[&quot;aa&quot;]</code>。</p>
<p>如果它是检查字符串<code>&quot;abab&quot;</code>，它将匹配到两个匹配项并且返回<code>[&quot;a&quot;, &quot;a&quot;]</code>，因为<code>a</code>字符不连续，在它们之间有一个<code>b</code>字符。最后，因为在字符串<code>&quot;bcd&quot;</code>中没有<code>&quot;a&quot;</code>，因此找不到匹配项。</p>
<p>当字母<code>z</code>在一行中出现一次或连续多次时，正则表达式<code>/z+/</code>会匹配到它。它会在以下所有字符串中找到匹配项：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"z"</span></span><br><span class="line"><span class="string">"zzzzzz"</span></span><br><span class="line"><span class="string">"ABCzzzz"</span></span><br><span class="line"><span class="string">"zzzzABC"</span></span><br><span class="line"><span class="string">"abczzzzzzzzzzzzzzzzzzzzzabc"</span></span><br></pre></td></tr></table></figure>



<h3 id="零次或多次的字符"><a href="#零次或多次的字符" class="headerlink" title="零次或多次的字符  *"></a>零次或多次的字符  *</h3><p>有一个选项可以匹配出现零次或多次的字符。</p>
<p>执行该操作的字符叫做<code>asterisk</code>或<code>star</code>，即<code>*</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> soccerWord = <span class="string">"gooooooooal!"</span>;</span><br><span class="line"><span class="keyword">let</span> gPhrase = <span class="string">"gut feeling"</span>;</span><br><span class="line"><span class="keyword">let</span> oPhrase = <span class="string">"over the moon"</span>;</span><br><span class="line"><span class="keyword">let</span> goRegex = <span class="regexp">/go*/</span>;</span><br><span class="line">soccerWord.match(goRegex); <span class="comment">// Returns ["goooooooo"]</span></span><br><span class="line">gPhrase.match(goRegex); <span class="comment">// Returns ["g"]</span></span><br><span class="line">oPhrase.match(goRegex); <span class="comment">// Returns null</span></span><br></pre></td></tr></table></figure>



<h3 id="用惰性匹配来查找字符-？"><a href="#用惰性匹配来查找字符-？" class="headerlink" title="用惰性匹配来查找字符 ？"></a>用惰性匹配来查找字符 ？</h3><p>在正则表达式中，<code>贪婪</code>匹配会匹配到符合正则表达式匹配模式的字符串的最长可能部分，并将其作为匹配项返回。另一种方案称为<code>懒惰</code>匹配，它会匹配到满足正则表达式的字符串的最小可能部分。</p>
<p>你可以将正则表达式<code>/t[a-z]*i/</code>应用于字符串<code>&quot;titanic&quot;</code>。这个正则表达式是一个以<code>t</code>开始，以<code>i</code>结束，并且中间有一些字母的匹配模式。</p>
<p>正则表达式默认是<code>贪婪</code>匹配，因此匹配返回为<code>[&quot;titani&quot;]</code>。它会匹配到适合该匹配模式的最大子字符串。</p>
<p>但是，你可以使用<code>?</code>字符来将其变成<code>懒惰</code>匹配。调整后的正则表达式<code>/t[a-z]*?i/</code>匹配字符串<code>&quot;titanic&quot;</code>返回<code>[&quot;ti&quot;]</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> text = <span class="string">"&lt;h1&gt;Winter is coming&lt;/h1&gt;"</span>;</span><br><span class="line"><span class="keyword">let</span> myRegex = <span class="regexp">/&lt;.*?&gt;/</span>; </span><br><span class="line"><span class="keyword">let</span> result = text.match(myRegex);</span><br><span class="line"><span class="comment">//返回 HTML 标签&lt;h1&gt;，而不是文本"&lt;h1&gt;Winter is coming&lt;/h1&gt;"。</span></span><br></pre></td></tr></table></figure>



<h3 id="字符串的开头"><a href="#字符串的开头" class="headerlink" title="字符串的开头 ^"></a>字符串的开头 ^</h3><p>先前的挑战表明，正则表达式可以用于查找许多匹配项。它们还用于搜寻字符串中特定位置的匹配模式。</p>
<p>在之前的挑战中，你使用<code>字符集</code>中的<code>插入</code>符号（<code>^</code>）来创建一个<code>否定字符集</code>，形如<code>[^thingsThatWillNotBeMatched]</code>。在<code>字符集</code>之外，<code>插入</code>符号用于字符串的开头搜寻匹配模式。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> firstString = <span class="string">"Ricky is first and can be found."</span>;</span><br><span class="line"><span class="keyword">let</span> firstRegex = <span class="regexp">/^Ricky/</span>;</span><br><span class="line">firstRegex.test(firstString);</span><br><span class="line"><span class="comment">// Returns true</span></span><br><span class="line"><span class="keyword">let</span> notFirst = <span class="string">"You can't find Ricky now."</span>;</span><br><span class="line">firstRegex.test(notFirst);</span><br><span class="line"><span class="comment">// Returns false</span></span><br></pre></td></tr></table></figure>



<h3 id="字符串的末尾"><a href="#字符串的末尾" class="headerlink" title="字符串的末尾 $"></a>字符串的末尾 $</h3><p>还有一种方法可以搜寻字符串末尾的匹配模式。</p>
<p>你可以使用正则表达式的<code>美元</code>符号<code>$</code>来搜寻字符串的结尾。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> theEnding = <span class="string">"This is a never ending story"</span>;</span><br><span class="line"><span class="keyword">let</span> storyRegex = <span class="regexp">/story$/</span>;</span><br><span class="line">storyRegex.test(theEnding);</span><br><span class="line"><span class="comment">// Returns true</span></span><br><span class="line"><span class="keyword">let</span> noEnding = <span class="string">"Sometimes a story will have to end"</span>;</span><br><span class="line">storyRegex.test(noEnding);</span><br><span class="line"><span class="comment">// Returns false</span></span><br></pre></td></tr></table></figure>

<blockquote>
</blockquote>
<h3 id="所有的字母和数字-w"><a href="#所有的字母和数字-w" class="headerlink" title="所有的字母和数字 \w"></a>所有的字母和数字 \w</h3><p>使用字符类，你可以使用<code>[a-z]</code>搜寻字母表中的所有字母。这种字符类是很常见的，它有一个缩写，但这个缩写也包含额外的字符。</p>
<p>JavaScript 中与字母表匹配的最接近的字符类是<code>\w</code>，这个缩写等同于<code>[A-Za-z0-9_]</code>。它不仅可以匹配大小写字母和数字，注意，它还会匹配下划线字符（<code>_</code>）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> longHand = <span class="regexp">/[A-Za-z0-9_]+/</span>;</span><br><span class="line"><span class="keyword">let</span> shortHand = <span class="regexp">/\w+/</span>;</span><br><span class="line"><span class="keyword">let</span> numbers = <span class="string">"42"</span>;</span><br><span class="line"><span class="keyword">let</span> varNames = <span class="string">"important_var"</span>;</span><br><span class="line">longHand.test(numbers); <span class="comment">// Returns true</span></span><br><span class="line">shortHand.test(numbers); <span class="comment">// Returns true</span></span><br><span class="line">longHand.test(varNames); <span class="comment">// Returns true</span></span><br><span class="line">shortHand.test(varNames); <span class="comment">// Returns true</span></span><br></pre></td></tr></table></figure>

<p>使用缩写<code>\w</code>来计算所有引号中字母和数字字符的数量。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> quoteSample = <span class="string">"The five boxing wizards jump quickly."</span>;</span><br><span class="line"><span class="keyword">let</span> alphabetRegexV2 = <span class="regexp">/\w/g</span>; <span class="comment">// 修改这一行</span></span><br><span class="line"><span class="keyword">let</span> result = quoteSample.match(alphabetRegexV2).length;</span><br></pre></td></tr></table></figure>



<h3 id="除了字母和数字的所有符号-W"><a href="#除了字母和数字的所有符号-W" class="headerlink" title="除了字母和数字的所有符号 \W"></a>除了字母和数字的所有符号 \W</h3><p>你可以使用<code>\W</code>搜寻和<code>\w</code>相反的匹配模式。注意，相反匹配模式使用大写字母。此缩写与<code>[^A-Za-z0-9_]</code>是一样的。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> shortHand = <span class="regexp">/\W/</span>;</span><br><span class="line"><span class="keyword">let</span> numbers = <span class="string">"42%"</span>;</span><br><span class="line"><span class="keyword">let</span> sentence = <span class="string">"Coding!"</span>;</span><br><span class="line">numbers.match(shortHand); <span class="comment">// Returns ["%"]</span></span><br><span class="line">sentence.match(shortHand); <span class="comment">// Returns ["!"]</span></span><br></pre></td></tr></table></figure>



<h3 id="匹配所有数字-amp-非数字-d-D"><a href="#匹配所有数字-amp-非数字-d-D" class="headerlink" title="匹配所有数字 &amp; 非数字  \d \D"></a>匹配所有数字 &amp; 非数字  \d \D</h3><p>查找数字字符的缩写是<code>\d</code>，注意是小写的<code>d</code>。这等同于字符类<code>[0-9]</code>，它查找 0 到 9 之间任意数字的单个字符。</p>
<p>查找非数字字符的缩写是<code>\D</code>。这等同于字符串<code>[^0-9]</code>，它查找不是 0 - 9 之间数字的单个字符。</p>
<h3 id="限制可能的用户名"><a href="#限制可能的用户名" class="headerlink" title="限制可能的用户名"></a>限制可能的用户名</h3><p>用户名在互联网上随处可见。它们是用户在自己喜欢的网站上的唯一身份。</p>
<p>你需要检查数据库中的所有用户名。以下是用户在创建用户名时必须遵守的一些简单规则。</p>
<p>1) 用户名中的数字必须在最后，且数字可以有零个或多个。</p>
<p>2) 用户名字母可以是小写字母和大写字母。</p>
<p>3) 用户名长度必须至少为两个字符。两位用户名只能使用字母。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> username = <span class="string">"JackOfAllTrades"</span>;</span><br><span class="line"><span class="keyword">let</span> userCheck = <span class="regexp">/^[a-z]&#123;2,&#125;\d*$/i</span>; <span class="comment">// 这一行</span></span><br><span class="line"><span class="keyword">let</span> result = userCheck.test(username);</span><br></pre></td></tr></table></figure>



<h3 id="匹配空白字符-amp-非空白字符"><a href="#匹配空白字符-amp-非空白字符" class="headerlink" title="匹配空白字符 &amp; 非空白字符"></a>匹配空白字符 &amp; 非空白字符</h3><p>匹配字母之间的空格。</p>
<p>以使用<code>\s</code>搜寻空格，其中<code>s</code>是小写。此匹配模式不仅匹配空格，还匹配回车符、制表符、换页符和换行符，你可以将其视为与<code>[\r\t\f\n\v]</code>类似。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> whiteSpace = <span class="string">"Whitespace. Whitespace everywhere!"</span></span><br><span class="line"><span class="keyword">let</span> spaceRegex = <span class="regexp">/\s/g</span>;</span><br><span class="line">whiteSpace.match(spaceRegex);</span><br><span class="line"><span class="comment">// Returns [" ", " "]</span></span><br></pre></td></tr></table></figure>

<p>也可以搜寻除了空格之外的所有内容。</p>
<p>使用<code>\S</code>搜寻非空白字符，其中<code>S</code>是大写。此匹配模式将不匹配空格、回车符、制表符、换页符和换行符。你可以认为这类似于字符类<code>[^\r\t\f\n\v]</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> whiteSpace = <span class="string">"Whitespace. Whitespace everywhere!"</span></span><br><span class="line"><span class="keyword">let</span> nonSpaceRegex = <span class="regexp">/\S/g</span>;</span><br><span class="line">whiteSpace.match(nonSpaceRegex).length; <span class="comment">// Returns 32</span></span><br></pre></td></tr></table></figure>



<h3 id="指定匹配的上限和下限"><a href="#指定匹配的上限和下限" class="headerlink" title="指定匹配的上限和下限"></a>指定匹配的上限和下限</h3><p>回想一下，你使用加号<code>+</code>查找一个或多个字符，使用星号<code>*</code>查找零个或多个字符。这些都很方便，但有时你需要匹配一定范围的匹配模式。</p>
<p>你可以使用<code>数量说明符</code>指定匹配模式的上下限。数量说明符与花括号（<code>{</code>和<code>}</code>）一起使用。你可以在花括号之间放两个数字，这两个数字代表匹配模式的上限和下限。</p>
<p>例如，要在字符串<code>&quot;ah&quot;</code>中匹配仅出现<code>3</code>到<code>5</code>次的字母<code>a</code>，你的正则表达式应为<code>/a{3,5}h/</code>。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> A4 = <span class="string">"aaaah"</span>;</span><br><span class="line"><span class="keyword">let</span> A2 = <span class="string">"aah"</span>;</span><br><span class="line"><span class="keyword">let</span> multipleA = <span class="regexp">/a&#123;3,5&#125;h/</span>;</span><br><span class="line">multipleA.test(A4); <span class="comment">// Returns true</span></span><br><span class="line">multipleA.test(A2); <span class="comment">// Returns false</span></span><br></pre></td></tr></table></figure>

<p><strong>只指定匹配的下限</strong></p>
<p>你可以使用带有花括号的<code>数量说明符</code>来指定匹配模式的上下限。但有时候你只想指定匹配模式的下限而不需要指定上限。</p>
<p>为此，在第一个数字后面跟一个逗号即可。</p>
<p>例如，要匹配至少出现<code>3</code>次字母<code>a</code>的字符串<code>&quot;hah&quot;</code>，你的正则表达式应该是<code>/ha{3,}h/</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> A4 = <span class="string">"haaaah"</span>;</span><br><span class="line"><span class="keyword">let</span> A2 = <span class="string">"haah"</span>;</span><br><span class="line"><span class="keyword">let</span> A100 = <span class="string">"h"</span> + <span class="string">"a"</span>.repeat(<span class="number">100</span>) + <span class="string">"h"</span>;</span><br><span class="line"><span class="keyword">let</span> multipleA = <span class="regexp">/ha&#123;3,&#125;h/</span>;</span><br><span class="line">multipleA.test(A4); <span class="comment">// Returns true</span></span><br><span class="line">multipleA.test(A2); <span class="comment">// Returns false</span></span><br><span class="line">multipleA.test(A100); <span class="comment">// Returns true</span></span><br></pre></td></tr></table></figure>

<p><strong>指定匹配的确切数量</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> A4 = <span class="string">"haaaah"</span>;</span><br><span class="line"><span class="keyword">let</span> A3 = <span class="string">"haaah"</span>;</span><br><span class="line"><span class="keyword">let</span> A100 = <span class="string">"h"</span> + <span class="string">"a"</span>.repeat(<span class="number">100</span>) + <span class="string">"h"</span>;</span><br><span class="line"><span class="keyword">let</span> multipleHA = <span class="regexp">/a&#123;3&#125;h/</span>;</span><br><span class="line">multipleHA.test(A4); <span class="comment">// Returns false</span></span><br><span class="line">multipleHA.test(A3); <span class="comment">// Returns true</span></span><br><span class="line">multipleHA.test(A100); <span class="comment">// Returns false</span></span><br></pre></td></tr></table></figure>



<h3 id="检查全部或无"><a href="#检查全部或无" class="headerlink" title="检查全部或无"></a>检查全部或无</h3><p>有时，你想要搜寻的匹配模式可能有不确定是否存在的部分。尽管如此，你还是想检查它们。</p>
<p>为此，你可以使用问号<code>?</code>指定可能存在的元素。这将<strong>检查前面的零个或一个元素</strong>。你可以将此符号视为前面的元素是可选的。</p>
<p>例如，美式英语和英式英语略有不同，你可以使用问号来匹配两种拼写。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> american = <span class="string">"color"</span>;</span><br><span class="line"><span class="keyword">let</span> british = <span class="string">"colour"</span>;</span><br><span class="line"><span class="keyword">let</span> rainbowRegex= <span class="regexp">/colou?r/</span>;</span><br><span class="line">rainbowRegex.test(american); <span class="comment">// Returns true</span></span><br><span class="line">rainbowRegex.test(british); <span class="comment">// Returns true</span></span><br></pre></td></tr></table></figure>



<h3 id="正向先行断言和负向先行断言"><a href="#正向先行断言和负向先行断言" class="headerlink" title="正向先行断言和负向先行断言"></a>正向先行断言和负向先行断言</h3><p><code>先行断言</code>是告诉 JavaScript 在字符串中向前查找的匹配模式。当你想要在同一个字符串上搜寻多个匹配模式时，这可能非常有用。</p>
<p>有两种<code>先行断言</code>：<code>正向先行断言</code>和<code>负向先行断言</code>。</p>
<p><code>正向先行断言</code>会查看并确保搜索匹配模式中的元素存在，但实际上并不匹配。正向先行断言的用法是<code>(?=...)</code>，其中<code>...</code>就是需要存在但不会被匹配的部分。</p>
<p>另一方面，<code>负向先行断言</code>会查看并确保搜索匹配模式中的元素不存在。负向先行断言的用法是<code>(?!...)</code>，其中<code>...</code>是你希望不存在的匹配模式。如果负向先行断言部分不存在，将返回匹配模式的其余部分。</p>
<p>尽管先行断言有点儿令人困惑，但是这些示例会有所帮助。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> quit = <span class="string">"qu"</span>;</span><br><span class="line"><span class="keyword">let</span> noquit = <span class="string">"qt"</span>;</span><br><span class="line"><span class="keyword">let</span> quRegex= <span class="regexp">/q(?=u)/</span>;</span><br><span class="line"><span class="keyword">let</span> qRegex = <span class="regexp">/q(?!u)/</span>;</span><br><span class="line">quit.match(quRegex); <span class="comment">// Returns ["q"]</span></span><br><span class="line">noquit.match(qRegex); <span class="comment">// Returns ["q"]</span></span><br></pre></td></tr></table></figure>

<p><code>先行断言</code>的更实际用途是检查一个字符串中的两个或更多匹配模式。这里有一个简单的密码检查器，密码规则是 3 到 6 个字符且至少包含一个数字：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> password = <span class="string">"abc123"</span>;</span><br><span class="line"><span class="keyword">let</span> checkPass = <span class="regexp">/(?=\w&#123;3,6&#125;)(?=\D*\d)/</span>;</span><br><span class="line">checkPass.test(password); <span class="comment">// Returns true</span></span><br></pre></td></tr></table></figure>

<p>在正则表达式<code>pwRegex</code>中使用<code>先行断言</code>以匹配至少5个字符且有两个连续数字的密码。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> sampleWord = <span class="string">"astronaut"</span>;</span><br><span class="line"><span class="keyword">let</span> pwRegex = <span class="regexp">/(?=\w&#123;5,&#125;)(?=\D*\d\d)/</span>; <span class="comment">// </span></span><br><span class="line"><span class="keyword">let</span> result = pwRegex.test(sampleWords); <span class="comment">//Returns true</span></span><br></pre></td></tr></table></figure>



<h3 id="使用捕获组重用模式"><a href="#使用捕获组重用模式" class="headerlink" title="使用捕获组重用模式"></a>使用捕获组重用模式</h3><p>一些你所搜寻的匹配模式会在字符串中出现多次，手动重复该正则表达式太浪费了。有一种更好的方法可以指定何时在字符串中会有多个重复的子字符串。</p>
<p>你可以使用<code>捕获组</code>搜寻重复的子字符串。括号<code>(</code>和<code>)</code>可以用来匹配重复的子字符串。你只需要把重复匹配模式的正则表达式放在括号中即可。</p>
<p>要指定重复字符串将出现的位置，可以使用反斜杠（<code>\</code>）后接一个数字。这个数字从 1 开始，随着你使用的每个捕获组的增加而增加。这里有一个示例，<code>\1</code>可以匹配第一个组。</p>
<p>下面的示例匹配任意两个被空格分割的单词：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> repeatStr = <span class="string">"regex regex"</span>;</span><br><span class="line"><span class="keyword">let</span> repeatRegex = <span class="regexp">/(\w+)\s\1/</span>;</span><br><span class="line">repeatRegex.test(repeatStr); <span class="comment">// Returns true</span></span><br><span class="line">repeatStr.match(repeatRegex); <span class="comment">// Returns ["regex regex", "regex"]</span></span><br></pre></td></tr></table></figure>



<p>在字符串上使用<code>.match()</code>方法将返回一个数组，其中包含它匹配的字符串及其捕获组。</p>
<p>在正则表达式<code>reRegex</code>中使用<code>捕获组</code>，以匹配在字符串中仅重复三次的数字，每一个都由空格分隔:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> repeatNum = <span class="string">"42 42 42"</span>;</span><br><span class="line"><span class="keyword">let</span> reRegex = <span class="regexp">/^(\d+)\s\1\s\1$/</span>; <span class="comment">// 修改这一行</span></span><br><span class="line"><span class="keyword">let</span> result = reRegex.test(repeatNum);</span><br><span class="line"><span class="built_in">console</span>.log(repeatNum.match(reRegex));<span class="comment">// ["42 42 42", "42"]</span></span><br></pre></td></tr></table></figure>



<h3 id="使用捕获组搜索和替换"><a href="#使用捕获组搜索和替换" class="headerlink" title="使用捕获组搜索和替换"></a>使用捕获组搜索和替换</h3><p>搜索功能是很有用的。但是，当你的搜索也执行更改（或替换）匹配文本的操作时，搜索功能就会显得更加强大。</p>
<p>可以使用字符串上<code>.replace()</code>方法来搜索并替换字符串中的文本。<code>.replace()</code>的输入首先是你想要搜索的正则表达式匹配模式，第二个参数是用于替换匹配的字符串或用于执行某些操作的函数。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> wrongText = <span class="string">"The sky is silver."</span>;</span><br><span class="line"><span class="keyword">let</span> silverRegex = <span class="regexp">/silver/</span>;</span><br><span class="line">wrongText.replace(silverRegex, <span class="string">"blue"</span>);</span><br><span class="line"><span class="comment">// Returns "The sky is blue."</span></span><br></pre></td></tr></table></figure>



<p>你还可以使用美元符号（<code>$</code>）访问替换字符串中的捕获组。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="string">"Code Camp"</span>.replace(<span class="regexp">/(\w+)\s(\w+)/</span>, <span class="string">'$2 $1'</span>);</span><br><span class="line"><span class="comment">// Returns "Camp Code"</span></span><br></pre></td></tr></table></figure>



<h3 id="删除开头和结尾的空白"><a href="#删除开头和结尾的空白" class="headerlink" title="删除开头和结尾的空白"></a>删除开头和结尾的空白</h3><p>有时字符串周围存在的空白字符并不是必需的。字符串的典型处理是删除字符串开头和结尾处的空格。</p>
<p>编写一个正则表达式并使用适当的字符串方法删除字符串开头和结尾的空格。</p>
<p><strong>注意：</strong><br><code>.trim()</code>方法在这里也可以实现同样的效果，但是现在使用正则表达式。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> hello = <span class="string">"   Hello, World!  "</span>;</span><br><span class="line"><span class="keyword">let</span> wsRegex = <span class="regexp">/^\s+|\s+$/g</span>; </span><br><span class="line"><span class="keyword">let</span> result = hello.replace(wsRegex,<span class="string">''</span>);</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/FCC/" rel="tag"># FCC</a>
          
            <a href="/tags/%E6%AD%A3%E5%88%99/" rel="tag"># 正则</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/05/07/03ES6/" rel="next" title="ECMAScript 6">
                <i class="fa fa-chevron-left"></i> ECMAScript 6
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/05/07/05%E5%9F%BA%E6%9C%AC%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/" rel="prev" title="基本数据结构">
                基本数据结构 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/agul1.png"
                alt="agul" />
            
              <p class="site-author-name" itemprop="name">agul</p>
              <p class="site-description motion-element" itemprop="description">天行健，君子以自强不息</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#正则表达式"><span class="nav-number">1.</span> <span class="nav-text">正则表达式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#介绍"><span class="nav-number">1.0.1.</span> <span class="nav-text">介绍</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用测试方法"><span class="nav-number">1.0.2.</span> <span class="nav-text">使用测试方法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串"><span class="nav-number">1.0.3.</span> <span class="nav-text">字符串</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#多种模式匹配文字字符串"><span class="nav-number">1.0.4.</span> <span class="nav-text">多种模式匹配文字字符串 |</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#忽略大小写-i"><span class="nav-number">1.0.5.</span> <span class="nav-text">忽略大小写 i</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#提取匹配项-match"><span class="nav-number">1.0.6.</span> <span class="nav-text">提取匹配项 .match()</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#全局匹配-g"><span class="nav-number">1.0.7.</span> <span class="nav-text">全局匹配  g</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#通配符-匹配任何内容"><span class="nav-number">1.0.8.</span> <span class="nav-text">通配符.匹配任何内容  .</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#单个字符有多种可能性"><span class="nav-number">1.0.9.</span> <span class="nav-text">单个字符有多种可能性 []</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#英文字母-a-z"><span class="nav-number">1.0.10.</span> <span class="nav-text">英文字母 [a-z]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数字和字母-a-z0-9"><span class="nav-number">1.0.11.</span> <span class="nav-text">数字和字母  [a-z0-9]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#不想匹配的字符"><span class="nav-number">1.0.12.</span> <span class="nav-text">不想匹配的字符 [^]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#出现一次或多次的字符"><span class="nav-number">1.0.13.</span> <span class="nav-text">出现一次或多次的字符  +</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#零次或多次的字符"><span class="nav-number">1.0.14.</span> <span class="nav-text">零次或多次的字符  *</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#用惰性匹配来查找字符-？"><span class="nav-number">1.0.15.</span> <span class="nav-text">用惰性匹配来查找字符 ？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串的开头"><span class="nav-number">1.0.16.</span> <span class="nav-text">字符串的开头 ^</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#字符串的末尾"><span class="nav-number">1.0.17.</span> <span class="nav-text">字符串的末尾 $</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#所有的字母和数字-w"><span class="nav-number">1.0.18.</span> <span class="nav-text">所有的字母和数字 \w</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#除了字母和数字的所有符号-W"><span class="nav-number">1.0.19.</span> <span class="nav-text">除了字母和数字的所有符号 \W</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#匹配所有数字-amp-非数字-d-D"><span class="nav-number">1.0.20.</span> <span class="nav-text">匹配所有数字 &amp; 非数字  \d \D</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#限制可能的用户名"><span class="nav-number">1.0.21.</span> <span class="nav-text">限制可能的用户名</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#匹配空白字符-amp-非空白字符"><span class="nav-number">1.0.22.</span> <span class="nav-text">匹配空白字符 &amp; 非空白字符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#指定匹配的上限和下限"><span class="nav-number">1.0.23.</span> <span class="nav-text">指定匹配的上限和下限</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#检查全部或无"><span class="nav-number">1.0.24.</span> <span class="nav-text">检查全部或无</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#正向先行断言和负向先行断言"><span class="nav-number">1.0.25.</span> <span class="nav-text">正向先行断言和负向先行断言</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用捕获组重用模式"><span class="nav-number">1.0.26.</span> <span class="nav-text">使用捕获组重用模式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用捕获组搜索和替换"><span class="nav-number">1.0.27.</span> <span class="nav-text">使用捕获组搜索和替换</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#删除开头和结尾的空白"><span class="nav-number">1.0.28.</span> <span class="nav-text">删除开头和结尾的空白</span></a></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">agul</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
